package com.syni.mdd.sjb.common.datatreaure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppMinappInfo;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppNews;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserChannel;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.mapper.DxshAppMinappInfoMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiAuroraPush.CommonPushDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.PushService;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.saasminapp.GroupInfoRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.apiAppNews.CreateNewsRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.BindGroupRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.SaveGroupInfoVo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lcc
 * @since 2020-10-22
 */
@Service
public class DxshAppMinappInfoServiceImpl extends ServiceImpl<DxshAppMinappInfoMapper, DxshAppMinappInfo> implements DxshAppMinappInfoService {
    private final Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    private DxshAppMinappInfoMapper dxshAppMinappInfoMapper;
    @Autowired
    private PushService pushService;
    @Autowired
    private DxshAppNewsService dxshAppNewsService;
    @Autowired
    private DxshAppUserNewsSwitchService dxshAppUserNewsSwitchService;
    @Autowired
    private DxshAppNewsPushService dxshAppNewsPushService;
    @Autowired
    private DxshAppUserChannelService dxshAppUserChannelService;

    @Value("${dxsh.group.domain:http}")
    private String groupDomain;

    @Override
    public Map<String, Object> saveMinappInfo(SaveGroupInfoVo saveGroupInfoVo) {
        //保存商圈相关信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppMinappInfo.STORE_ID, saveGroupInfoVo.getStoreId());
        DxshAppMinappInfo dxshAppMinappInfo = dxshAppMinappInfoMapper.selectOne(queryWrapper);
        if(dxshAppMinappInfo == null){
            DxshAppUserChannel dxshAppUserChannel = dxshAppUserChannelService.getByStoreId(saveGroupInfoVo.getStoreId());
            if(dxshAppUserChannel != null){
                dxshAppMinappInfo = new DxshAppMinappInfo();
                dxshAppMinappInfo.setNewTime(LocalDateTime.now());
                dxshAppMinappInfo.setStatus(Constants.MINAPP_ALREADY_BIND_FLAG);
                dxshAppMinappInfo.setGroupName(saveGroupInfoVo.getGroupName());
                dxshAppMinappInfo.setGroupLogo(saveGroupInfoVo.getGroupLogo());
                dxshAppMinappInfo.setUserId(dxshAppUserChannel.getUserId());
                dxshAppMinappInfo.setAppId(dxshAppUserChannel.getAppid());
                dxshAppMinappInfo.setMinName(dxshAppUserChannel.getMinAppName());
                dxshAppMinappInfo.setStoreId(dxshAppUserChannel.getStoreId());
                this.saveOrUpdate(dxshAppMinappInfo);
            }
        }

        //自定义消息
        Map<String,Object> contentMap = new HashMap<>();
        contentMap.put("groupName",saveGroupInfoVo.getGroupName());
        contentMap.put("title","关联商圈成功");
        contentMap.put("code",Constants.GROUP_BIND_SUCCESS_CODE);
        contentMap.put("storeId",saveGroupInfoVo.getStoreId());
        contentMap.put("newType","groupBindSuccess");

        if(dxshAppMinappInfo.getUserId() != null){
            //创建消息
            Integer newsId = null;
            String alert = "您已成功关联商圈【" + saveGroupInfoVo.getGroupName() + "】";
            String dxshAppNewsStr = pushGroupNews(contentMap,dxshAppMinappInfo.getUserId(),"关联商圈成功",alert);
            if(dxshAppNewsStr != null){
                Map<String,Object> dxshAppNewsMap = JSON.parseObject(dxshAppNewsStr, Map.class);
                DxshAppNews dxshAppNews = JSON.parseObject(JSON.toJSONString(dxshAppNewsMap.get("data")), DxshAppNews.class);
                newsId = dxshAppNews.getId();
            }

            contentMap.put("newsId",newsId.toString());

            customNews(contentMap,dxshAppMinappInfo.getUserId().toString(),alert);
        }
        return ResultMapHelper.success(null, ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> cancelRelation(SaveGroupInfoVo saveGroupInfoVo) {
        //自定义消息
        DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
        if(dxshAppMinappInfo != null){
            dxshAppMinappInfo.setApplyTime(LocalDateTime.now());
            dxshAppMinappInfoMapper.updateById(dxshAppMinappInfo);

            Map<String,Object> contentMap = new HashMap<>();
            contentMap.put("title","取消关联申请");
            contentMap.put("groupName",dxshAppMinappInfo.getGroupName());
            contentMap.put("applyTime", DateTimeUtils.converLocalDateTimeToLong(LocalDateTime.now()).toString());
            contentMap.put("minName",dxshAppMinappInfo.getMinName());
            contentMap.put("code",Constants.GROUP_CANCEL_APPLY_CODE);
            contentMap.put("storeId",dxshAppMinappInfo.getStoreId());
            contentMap.put("newType","groupCancelApply");

            //创建消息
            String alert = "商圈【" + dxshAppMinappInfo.getGroupName() + "】申请与您的小程序取消关联，请立即处理";
            String dxshAppNewsStr = pushGroupNews(contentMap,dxshAppMinappInfo.getUserId(), "取消关联申请处理", alert);
            Integer newsId = null;
            if(dxshAppNewsStr != null){
                Map<String,Object> dxshAppNewsMap = JSON.parseObject(dxshAppNewsStr, Map.class);
                DxshAppNews dxshAppNews = JSON.parseObject(JSON.toJSONString(dxshAppNewsMap.get("data")), DxshAppNews.class);
                newsId = dxshAppNews.getId();
            }


            contentMap.put("newsId",newsId.toString());
            if(dxshAppMinappInfo.getUserId() != null){
                customNews(contentMap,dxshAppMinappInfo.getUserId().toString(),alert);
            }
        }
        return ResultMapHelper.success(null, ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> cancelOperate(SaveGroupInfoVo saveGroupInfoVo) {
        final Integer STORE_CONFIRM_FLAG = 1;  //商户点击确认取消关联

        //设置消息为已读
        DxshAppNews dxshAppNews = dxshAppNewsService.getById(saveGroupInfoVo.getNewsId());
        dxshAppNews.setIsWatch(Constants.COMMON_FLAG_TRUE_INT);
        dxshAppNewsService.saveOrUpdate(dxshAppNews);
        //通知商圈
        try{
//            String url = "http://cybcms.syni.com/cybcms/api/noticeSqCancelAssociation";
            String url =  groupDomain +"/cybcms/api/noticeSqCancelAssociation";
            Map<String,Object> paramsMap = new HashMap<>();
            paramsMap.put("storeId",saveGroupInfoVo.getStoreId());
            paramsMap.put("type",saveGroupInfoVo.getOperateStatus());
            String forEntity = RestTemplateUtils.getForEntity(url, paramsMap);
            Map<String,Object> resultMap = (Map)JSON.parse(forEntity);
            log.info("=========resultMap========{}",resultMap);
            if(StringUtils.equals(resultMap.get("retCode").toString(),"10000")){
                if(saveGroupInfoVo.getOperateStatus().equals(STORE_CONFIRM_FLAG)){
                    DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
                    if(dxshAppMinappInfo != null){
                        dxshAppMinappInfoMapper.deleteById(dxshAppMinappInfo);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> quitBusinessGroup(SaveGroupInfoVo saveGroupInfoVo) {
        try{
            //        String url = "http://cybcms.syni.com/cybcms/api/noticeCancelAssociation";
            String url = groupDomain +"/cybcms/api/noticeCancelAssociation";
            Map<String,Object> params = new LinkedHashMap<>();
            params.put("storeId",saveGroupInfoVo.getStoreId());
            String forEntity = RestTemplateUtils.getForEntity(url, params);
            Map<String,Object> resultMap = (Map)JSON.parse(forEntity);
            if(resultMap != null && Integer.parseInt(resultMap.get("retCode").toString()) == 10000){
                DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
                dxshAppMinappInfo.setStatus(Constants.MINAPP_WAIT_CONFIRM_FLAG);
                dxshAppMinappInfo.setApplyTime(DateTimeUtils.converDateToLocalDateTime(DateTimeUtils.converLongToDate(saveGroupInfoVo.getQuitTime())));
                dxshAppMinappInfoMapper.updateById(dxshAppMinappInfo);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> cancelOrConfirmNews(SaveGroupInfoVo saveGroupInfoVo) {
        final Integer BUSINESS_CONFIRM_FLAG = 1;  //商圈点击确认取消关联
        final Integer BUSINESS_REJECT_FLAG = 2;   //商圈点击拒绝取消关联

        String dxshAppNewsStr = null;
        Map<String,Object> contentMap = new HashMap<>();

        DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
        String alert ="";
        if(dxshAppMinappInfo != null){
            contentMap.put("groupName",dxshAppMinappInfo.getGroupName());
            contentMap.put("applyTime",String.valueOf(DateTimeUtils.converLocalDateTimeToLong(dxshAppMinappInfo.getApplyTime())));
            //创建消息
            if(saveGroupInfoVo.getOperateStatus().equals(BUSINESS_CONFIRM_FLAG)){
                contentMap.put("title","取消关联商圈成功");
                contentMap.put("code",Constants.GROUP_CANCEL_SUCCESS_CODE);
                contentMap.put("newType","groupCancelSuccess");

                alert = "您已与商圈【" + dxshAppMinappInfo.getGroupName() + "】取消关联，可重新关联新商圈";
                dxshAppNewsStr = pushGroupNews(contentMap,saveGroupInfoVo.getUserId(), "取消关联商圈成功", alert);

                dxshAppMinappInfoMapper.deleteById(dxshAppMinappInfo);
            }else if(saveGroupInfoVo.getOperateStatus().equals(BUSINESS_REJECT_FLAG)){
                contentMap.put("title","商圈拒绝取消关联");
                contentMap.put("code",Constants.GROUP_REJECT_CANCEL_CODE);
                contentMap.put("newType","groupRejectCancel");

                alert = "商圈【" + dxshAppMinappInfo.getGroupName() + "】已拒绝您的取消关联申请，请重新尝试";
                dxshAppNewsStr = pushGroupNews(contentMap,saveGroupInfoVo.getUserId(), "商圈拒绝取消关联", alert);

                dxshAppMinappInfo.setStatus(Constants.MINAPP_ALREADY_BIND_FLAG);
                dxshAppMinappInfoMapper.updateById(dxshAppMinappInfo);
            }
            //自定义消息
            if(dxshAppNewsStr != null){
                Map<String,Object> dxshAppNewsMap = JSON.parseObject(dxshAppNewsStr, Map.class);
                DxshAppNews dxshAppNews = JSON.parseObject(JSON.toJSONString(dxshAppNewsMap.get("data")), DxshAppNews.class);
                contentMap.put("newsId",dxshAppNews.getId().toString());
            }else{
                contentMap.put("newsId",null);
            }

            if(dxshAppMinappInfo.getUserId() != null) {
                customNews(contentMap, dxshAppMinappInfo.getUserId().toString(), alert);
            }
        }

        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> clickQuitBtn(Integer newsId) {
        DxshAppNews dxshAppNews = dxshAppNewsService.getById(newsId);
        dxshAppNews.setIsWatch(Constants.COMMON_FLAG_TRUE_INT);
        dxshAppNewsService.saveOrUpdate(dxshAppNews);
        return ResultMapHelper.success(null, ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> dividedNews(SaveGroupInfoVo saveGroupInfoVo) {
        String dxshAppNewsStr = null;
        DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
        if(dxshAppMinappInfo != null){
            //自定义消息
            Map<String,Object> contentMap = new HashMap<>();
            contentMap.put("groupName",dxshAppMinappInfo.getGroupName());
            contentMap.put("divideRatio",saveGroupInfoVo.getDivideRatio());
            contentMap.put("title","分账比例确认");
            contentMap.put("code",Constants.GROUP_DIVIDED_CONFIRM_CODE);
            contentMap.put("storeId",dxshAppMinappInfo.getStoreId());
            contentMap.put("newType","groupDividedConfirm");

            //创建消息
            String alert = "商圈【" + dxshAppMinappInfo.getGroupName() + "】申请调整分账比例，请及时处理";
            dxshAppNewsStr = pushGroupNews(contentMap,saveGroupInfoVo.getUserId(), "分账比例确认", alert);


            if(dxshAppNewsStr != null){
                Map<String,Object> dxshAppNewsMap = JSON.parseObject(dxshAppNewsStr, Map.class);
                DxshAppNews dxshAppNews = JSON.parseObject(JSON.toJSONString(dxshAppNewsMap.get("data")), DxshAppNews.class);
                contentMap.put("newsId",dxshAppNews.getId().toString());
            }else{
                contentMap.put("newsId",null);
            }
            if(dxshAppMinappInfo.getUserId() != null) {
                customNews(contentMap, dxshAppMinappInfo.getUserId().toString(), alert);
            }

            /*dxshAppMinappInfo.setDivideRatio(saveGroupInfoVo.getDivideRatio());
            dxshAppMinappInfoMapper.updateById(dxshAppMinappInfo);*/
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> confirmDivided(SaveGroupInfoVo saveGroupInfoVo) {
        final Integer STORE_REJECT_FLAG = 2;   //商户点击拒绝分账比例
        final Integer STORE_ACCEPT_FLAG = 1;   //商户点击接受分账比例

        //消息设为已读
        DxshAppNews dxshAppNews = dxshAppNewsService.getById(saveGroupInfoVo.getNewsId());
        dxshAppNews.setIsWatch(Constants.COMMON_FLAG_TRUE_INT);
        dxshAppNewsService.saveOrUpdate(dxshAppNews);

        //通知商圈
        try{
            //        String url = "http://cybcms.syni.com/cybcms/api/confirmLedgerAccount";
            String url =  groupDomain + "/cybcms/api/confirmLedgerAccount";
            Map<String,Object> params = new LinkedHashMap<>();
            params.put("storeId",saveGroupInfoVo.getStoreId());
            params.put("type",saveGroupInfoVo.getOperateStatus());
            String forEntity = RestTemplateUtils.getForEntity(url, params);
            Map<String,Object> resultMap = (Map)JSON.parse(forEntity);
            if(resultMap != null && Integer.parseInt(resultMap.get("retCode").toString()) == 10000){
                DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
                if(saveGroupInfoVo.getOperateStatus().equals(STORE_ACCEPT_FLAG)){
                    dxshAppMinappInfo.setDivideRatio(saveGroupInfoVo.getDivideRatio());
                    dxshAppMinappInfoMapper.updateById(dxshAppMinappInfo);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> getGroupInfo(SaveGroupInfoVo saveGroupInfoVo) {
        DxshAppMinappInfo dxshAppMinappInfo = findByStoreId(saveGroupInfoVo.getStoreId());
        GroupInfoRpVo groupInfoRpVo = new GroupInfoRpVo();
        if(dxshAppMinappInfo != null){
            BeanUtils.copyProperties(dxshAppMinappInfo,groupInfoRpVo);
        }
        return ResultMapHelper.success(groupInfoRpVo,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> bindGroup(BindGroupRqVo bindGroupRqVo) {
        /*QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppMinappInfo.USER_ID,bindGroupRqVo.getUserId());
        queryWrapper.eq(DxshAppMinappInfo.STORE_ID,bindGroupRqVo.getStoreId());
        DxshAppMinappInfo dxshAppMinappInfo = dxshAppMinappInfoMapper.selectOne(queryWrapper);
        if(dxshAppMinappInfo == null){
            dxshAppMinappInfo = new DxshAppMinappInfo();
            BeanUtils.copyProperties(bindGroupRqVo,dxshAppMinappInfo);
            dxshAppMinappInfoMapper.insert(dxshAppMinappInfo);
        }*/
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public DxshAppMinappInfo findByStoreId(String storeId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppMinappInfo.STORE_ID,storeId);
        return dxshAppMinappInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public void syncDxshMinAppInfos(List<DxshAppMinappInfo> dxshAppMinappInfos) {

    }

    @Override
    public Map<String, DxshAppMinappInfo> getMapByStoreIds(Set<String> storeIds) {
        Map<String,DxshAppMinappInfo> dxshAppMinappInfoMap = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in(DxshAppMinappInfo.STORE_ID,storeIds);
        List<DxshAppMinappInfo> dxshAppMinappInfos = dxshAppMinappInfoMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppMinappInfos)){
            dxshAppMinappInfos.forEach(di -> {
                dxshAppMinappInfoMap.put(di.getStoreId(),di);
            });

        }
        return dxshAppMinappInfoMap;
    }

    /**
     * 创建商圈信息
     * @param userId  用户标识
     * @param describes  标题
     * @param title      具体内容
     * @return
     */
    public String pushGroupNews(Map<String,Object> contentMap,Integer userId,String describes,String title){
        CreateNewsRqVo createNewsRqVo = new CreateNewsRqVo();
        createNewsRqVo.setUserId(userId);
        createNewsRqVo.setMessageType(Constants.DANK_OTHER_INFORM);
        createNewsRqVo.setMessageSecondType(Constants.DANK_OTHER_INFORM_MINAPP);
        createNewsRqVo.setType(1);
        createNewsRqVo.setMainTitle("其他消息");
        createNewsRqVo.setDescribes(describes);
        createNewsRqVo.setTitle(title);
        createNewsRqVo.setContent(JSON.toJSONString(contentMap));
        DxshAppNews dxshAppNews = dxshAppNewsService.createNews(createNewsRqVo);
        if(dxshAppNews != null) {
            return JSON.toJSONString(ResultMapHelper.success(dxshAppNews,ResultMsg.MSG_GET_SUCCESS));
        }else{
            return null;
        }
    }

    public void customNews(Map<String,Object> contentMap,String userId,String alert){
        final Integer BUSINESS_CHANNEL_FLAG = 2;   //商家端
        final Integer CUSTOM_PUSH_FLAG = 2;   //自定义消息推送
        final Integer NAVIGATE_PUSH_FLAG = 1;   //通知消息推送
        CommonPushDto commonPushDto = new CommonPushDto();
        commonPushDto.setPushApplication(BUSINESS_CHANNEL_FLAG);
        commonPushDto.setContent(JSON.toJSONString(contentMap,SerializerFeature.WriteNullStringAsEmpty));
        commonPushDto.setAlias(JSON.toJSONString(new ArrayList<>(Arrays.asList(Constants.BUSINESS_DXSH_PREFIX + userId))));
        commonPushDto.setJiPushType(CUSTOM_PUSH_FLAG);
        pushService.commonCustomMessage(commonPushDto);

        Set<Integer> types = dxshAppUserNewsSwitchService.getNewsSwitchByUserId_v2(Integer.parseInt(userId),
                Constants.DANK_OTHER_INFORM,Constants.DANK_OTHER_INFORM_MINAPP);
        if(types.contains(Constants.DANK_OTHER_INFORM_MINAPP) && dxshAppNewsPushService.checkHavePush(Integer.parseInt(userId))){
            //判断时段
            commonPushDto.setAlert(alert);
            commonPushDto.setJiPushType(NAVIGATE_PUSH_FLAG);
            pushService.commonCustomMessage(commonPushDto);
        }
    }


}
